const util = require('../../utils/util.js');

Page({
  data: {
    userInfo: {},
    hasUserInfo: false,
    canIUseGetUserProfile: false,
    bmi: 0,
    bmiStatus: { status: '', color: '' },
    height: 170, // 默认身高
    weight: 60,  // 默认体重
    weightRecords: [],
    todayWeight: null,
    latestRecord: null,
    isLatestRecordToday: false, // 添加判断最新记录是否为今天的标志
    healthPlans: [],
    completedPlans: 0,
    totalPlans: 0,
    showAddWeightModal: false,
    newWeight: ''
  },

  onLoad: function () {
    // 检查是否可以使用 getUserProfile API
    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true
      });
    }
    
    // 获取本地存储的体重记录
    this.loadWeightRecords();
    
    // 获取健康计划
    this.loadHealthPlans();
  },

  onShow: function () {
    // 每次页面显示时重新加载数据
    this.loadWeightRecords();
    this.loadHealthPlans();
  },

  // 加载体重记录
  loadWeightRecords: function () {
    const weightRecords = wx.getStorageSync('weightRecords') || [];
    const today = util.formatDate(new Date());
    
    // 查找今天的记录
    const todayRecord = weightRecords.find(record => record.date === today);
    
    // 获取最新记录
    const latestRecord = weightRecords.length > 0 
      ? weightRecords[weightRecords.length - 1] 
      : null;
    
    // 判断最新记录是否为今天的记录
    const isLatestRecordToday = latestRecord && latestRecord.date === today;
    
    // 更新体重和BMI数据
    const weight = (todayRecord ? todayRecord.weight : (latestRecord ? latestRecord.weight : this.data.weight));
    const height = wx.getStorageSync('userHeight') || this.data.height;
    const bmi = util.calculateBMI(weight, height);
    
    this.setData({
      weightRecords,
      todayWeight: todayRecord ? todayRecord.weight : null,
      latestRecord,
      isLatestRecordToday, // 设置是否为今天的记录
      weight,
      height,
      bmi,
      bmiStatus: util.getBMIStatus(bmi)
    });
  },

  // 加载健康计划
  loadHealthPlans: function () {
    const healthPlans = wx.getStorageSync('healthPlans') || [];
    const today = util.formatDate(new Date());
    
    // 统计今日完成的计划数量
    const completedPlans = healthPlans.filter(plan => plan.completed).length;
    
    this.setData({
      healthPlans,
      completedPlans,
      totalPlans: healthPlans.length
    });
  },

  // 获取用户信息
  getUserProfile: function () {
    wx.getUserProfile({
      desc: '用于完善用户资料',
      success: (res) => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        });
        
        // 存储用户信息
        wx.setStorageSync('userInfo', res.userInfo);
      }
    });
  },

  // 显示添加体重弹窗
  showAddWeightModal: function () {
    this.setData({
      showAddWeightModal: true,
      newWeight: this.data.weight.toString()
    });
  },

  // 隐藏添加体重弹窗
  hideAddWeightModal: function () {
    this.setData({
      showAddWeightModal: false
    });
  },

  // 监听输入体重变化
  onWeightInput: function (e) {
    this.setData({
      newWeight: e.detail.value
    });
  },

  // 添加体重记录
  addWeightRecord: function () {
    const newWeight = parseFloat(this.data.newWeight);
    
    if (isNaN(newWeight) || newWeight <= 0) {
      wx.showToast({
        title: '请输入有效的体重数值',
        icon: 'none'
      });
      return;
    }
    
    const today = util.formatDate(new Date());
    const weightRecords = wx.getStorageSync('weightRecords') || [];
    
    // 检查今天是否已有记录
    const todayIndex = weightRecords.findIndex(record => record.date === today);
    
    if (todayIndex >= 0) {
      // 更新今天的记录
      weightRecords[todayIndex].weight = newWeight;
    } else {
      // 添加新记录
      weightRecords.push({
        date: today,
        weight: newWeight
      });
    }
    
    // 保存到本地存储
    wx.setStorageSync('weightRecords', weightRecords);
    
    // 隐藏弹窗并刷新数据
    this.setData({
      showAddWeightModal: false
    });
    
    this.loadWeightRecords();
    
    wx.showToast({
      title: '体重记录已保存',
      icon: 'success'
    });
  },

  // 导航到体重记录页面
  navigateToWeight: function () {
    wx.switchTab({
      url: '/pages/weight/weight'
    });
  },

  // 导航到健康计划页面
  navigateToHealthPlan: function () {
    wx.switchTab({
      url: '/pages/plan/plan'
    });
  }
}); 